import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:m2_flutter/data/config.dart';
import 'package:m2_flutter/data/method_bean.dart';
import 'package:m2_flutter/page/AgreementPage.dart';
import 'package:m2_flutter/page/InputPage.dart';
import 'package:m2_flutter/service/SqlManager.dart';

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  DateTime dateNow = DateTime.now();
  double money = 0;
  List<Map>? list = [];
  @override
  void initState() {
    super.initState();
    init();
  }

  Future<void> init() async {
    money = 0;
    list = await SqlManager.getByDate(dateNow);
    print(list);
    for (var element in list!) {
      money = money + int.parse(element["money"].toString());
    }
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle(
        statusBarColor: Colors.transparent,
        statusBarIconBrightness: Brightness.light));
    var size = MediaQuery.of(context).size;
    return Scaffold(
        body: Column(
      children: [
        Container(
          color: Config.color_main,
          height: size.height / 3,
          width: double.infinity,
          child: SafeArea(
            child: Padding(
              padding: const EdgeInsets.only(top: 10),
              child: Column(
                children: [
                  InkWell(
                    onTap: () async {
                      int yearCount = DateTime.now().year - 1999;
                      int selectYear = 0;
                      int selectMonth = 0;
                      DateTime? time = await showModalBottomSheet(
                          isScrollControlled: true,
                          context: context,
                          builder: (c) => StatefulBuilder(
                                builder: (context, state) {
                                  return AnimatedPadding(
                                    padding: MediaQuery.of(context).viewInsets,
                                    duration: Duration.zero,
                                    child: SingleChildScrollView(
                                        child: Column(
                                      children: [
                                        Padding(
                                          padding: const EdgeInsets.symmetric(
                                              vertical: 5),
                                          child: Stack(
                                            children: [
                                              SizedBox(
                                                width: double.infinity,
                                                child: Column(
                                                  children: [
                                                    const Text(
                                                      "选择年月",
                                                      style: TextStyle(
                                                          fontWeight:
                                                              FontWeight.bold),
                                                    ),
                                                    Text(
                                                        "${selectYear + 2000}年${selectMonth + 1}月")
                                                  ],
                                                ),
                                              ),
                                              Positioned(
                                                  right: 0,
                                                  child: Padding(
                                                    padding:
                                                        const EdgeInsets.all(5),
                                                    child: InkWell(
                                                      onTap: () {
                                                        Navigator.pop(
                                                            context,
                                                            DateTime(
                                                                selectYear +
                                                                    2000,
                                                                selectMonth +
                                                                    1));
                                                      },
                                                      child: Container(
                                                          decoration: const BoxDecoration(
                                                              borderRadius:
                                                                  BorderRadius
                                                                      .all(Radius
                                                                          .circular(
                                                                              5)),
                                                              color:
                                                                  Colors.blue),
                                                          child: const Padding(
                                                            padding: EdgeInsets
                                                                .symmetric(
                                                                    horizontal:
                                                                        15,
                                                                    vertical:
                                                                        5),
                                                            child: Text(
                                                              "完成",
                                                              style: TextStyle(
                                                                  color: Colors
                                                                      .white),
                                                            ),
                                                          )),
                                                    ),
                                                  ))
                                            ],
                                          ),
                                        ),
                                        Padding(
                                          padding: const EdgeInsets.all(8.0),
                                          child: SizedBox(
                                            height: MediaQuery.of(context)
                                                    .size
                                                    .height *
                                                0.3,
                                            child: Stack(
                                              children: [
                                                Positioned.fill(
                                                    child: Row(
                                                  children: [
                                                    Expanded(
                                                        child: PageView.builder(
                                                            controller: PageController(
                                                                viewportFraction:
                                                                    0.2,
                                                                initialPage:
                                                                    yearCount),
                                                            onPageChanged: (i) {
                                                              state(() {
                                                                selectYear = i;
                                                              });
                                                            },
                                                            scrollDirection:
                                                                Axis.vertical,
                                                            itemCount:
                                                                yearCount,
                                                            itemBuilder:
                                                                (c, i) {
                                                              return Padding(
                                                                padding: const EdgeInsets
                                                                        .symmetric(
                                                                    horizontal:
                                                                        5,
                                                                    vertical:
                                                                        3),
                                                                child: Container(
                                                                    decoration: BoxDecoration(
                                                                        color: Colors
                                                                            .white,
                                                                        borderRadius: const BorderRadius.all(Radius.circular(5)),
                                                                        boxShadow: [
                                                                          BoxShadow(
                                                                              color: Colors.grey.withAlpha(10),
                                                                              blurRadius: 5,
                                                                              spreadRadius: 5)
                                                                        ]),
                                                                    child: Center(
                                                                        child: Text(
                                                                            "${2000 + i}年"))),
                                                              );
                                                            })),
                                                    Expanded(
                                                        child: PageView.builder(
                                                            controller:
                                                                PageController(
                                                                    viewportFraction:
                                                                        0.2),
                                                            onPageChanged: (i) {
                                                              state(() {
                                                                selectMonth = i;
                                                              });
                                                            },
                                                            scrollDirection:
                                                                Axis.vertical,
                                                            itemCount: 12,
                                                            pageSnapping: false,
                                                            itemBuilder:
                                                                (c, i) {
                                                              return Padding(
                                                                padding: const EdgeInsets
                                                                        .symmetric(
                                                                    horizontal:
                                                                        5,
                                                                    vertical:
                                                                        3),
                                                                child: Container(
                                                                    decoration: BoxDecoration(
                                                                        color: Colors
                                                                            .white,
                                                                        borderRadius: const BorderRadius.all(Radius.circular(5)),
                                                                        boxShadow: [
                                                                          BoxShadow(
                                                                              color: Colors.grey.withAlpha(10),
                                                                              blurRadius: 5,
                                                                              spreadRadius: 5)
                                                                        ]),
                                                                    child: Center(
                                                                        child: Text(
                                                                            "${i + 1}月"))),
                                                              );
                                                            })),
                                                  ],
                                                )),
                                                Positioned.fill(
                                                    child: IgnorePointer(
                                                  child: Center(
                                                    child: Container(
                                                      width: double.infinity,
                                                      height: 50,
                                                      decoration: BoxDecoration(
                                                          borderRadius:
                                                              const BorderRadius
                                                                      .all(
                                                                  Radius
                                                                      .circular(
                                                                          5)),
                                                          border: Border.all(
                                                              color:
                                                                  Colors.blue),
                                                          color: Colors
                                                              .lightBlueAccent
                                                              .withAlpha(20)),
                                                    ),
                                                  ),
                                                ))
                                              ],
                                            ),
                                          ),
                                        ),
                                        const SizedBox(
                                          height: 10,
                                        ),
                                      ],
                                    )),
                                  );
                                },
                              ));
                      if (time != null) {
                        setState(() {
                          dateNow = time;
                        });
                      }
                    },
                    child: Container(
                      decoration: BoxDecoration(
                          color: Config.color_yellow,
                          borderRadius:
                              const BorderRadius.all(Radius.circular(5))),
                      child: Padding(
                          padding: const EdgeInsets.symmetric(
                              horizontal: 10, vertical: 10),
                          child: Text("${dateNow.year}年${dateNow.month}月")),
                    ),
                  ),
                  Expanded(
                    child: Center(
                      child: Row(
                        children: [
                          Image.asset(
                            'assets/logo.png',
                            scale: 4,
                          ),
                          Padding(
                            padding: const EdgeInsets.only(left: 20),
                            child: Column(
                              children: [
                                Text(
                                  "￥$money",
                                  style: const TextStyle(
                                      color: Colors.white, fontSize: 30),
                                ),
                                const Text(
                                  "支出/元",
                                  style: TextStyle(
                                    color: Colors.white,
                                  ),
                                ),
                              ],
                              crossAxisAlignment: CrossAxisAlignment.start,
                              mainAxisAlignment: MainAxisAlignment.center,
                            ),
                          )
                        ],
                        mainAxisAlignment: MainAxisAlignment.center,
                      ),
                    ),
                  )
                ],
              ),
            ),
          ),
        ),
        Expanded(
            child: Column(
          children: [
            SizedBox(
              height: size.height * 0.15,
              child: Center(
                child: InkWell(
                  onTap: () async {
                    await Navigator.push(
                        context,
                        MaterialPageRoute(
                            builder: (c) => InputPage(
                                bean: MethodBean(type: 'insert', id: ""))));
                    init();
                  },
                  child: Container(
                    decoration: BoxDecoration(
                        color: Config.color_orange,
                        borderRadius:
                            const BorderRadius.all(Radius.circular(5))),
                    child: const Padding(
                        padding:
                            EdgeInsets.symmetric(horizontal: 50, vertical: 14),
                        child: Text(
                          "记一笔",
                          style: TextStyle(color: Colors.white),
                        )),
                  ),
                ),
              ),
            ),
            if (list!.isEmpty)
              Padding(
                padding: const EdgeInsets.symmetric(horizontal: 50),
                child: Container(
                  decoration: BoxDecoration(
                      color: Colors.grey[300],
                      borderRadius: const BorderRadius.all(Radius.circular(5))),
                  child: const Padding(
                      padding: EdgeInsets.all(10),
                      child: Text(
                        "*使用教程\n感谢使用M2记账本，我们的理念是打造一款简约的记账APP。\n点击上方【记一笔】记录今天的支出\n点击上方日期可查看每月详细支出",
                      )),
                ),
              )
            else
              Expanded(
                child: ListView.separated(
                    itemBuilder: (context, index) {
                      return InkWell(
                        onTap: () async {
                          await Navigator.push(
                              context,
                              MaterialPageRoute(
                                  builder: (c) => InputPage(
                                      bean: MethodBean(
                                          type: "update",
                                          id: list![index]["id"].toString()))));
                          init();
                        },
                        onLongPress: () async {
                          bool? res = await showDialog(
                              context: context,
                              builder: (c) => SimpleDialog(
                                    title: const Text("是否删除？"),
                                    children: [
                                      const SizedBox(
                                        height: 20,
                                      ),
                                      Padding(
                                        padding: const EdgeInsets.symmetric(
                                            horizontal: 20),
                                        child: Row(
                                          mainAxisAlignment:
                                              MainAxisAlignment.end,
                                          children: [
                                            InkWell(
                                                onTap: () {
                                                  Navigator.pop(context, false);
                                                },
                                                child: Container(
                                                    decoration:
                                                        const BoxDecoration(
                                                            color: Colors.grey,
                                                            borderRadius:
                                                                BorderRadius
                                                                    .all(Radius
                                                                        .circular(
                                                                            5))),
                                                    child: const Padding(
                                                      padding:
                                                          EdgeInsets.symmetric(
                                                              horizontal: 15,
                                                              vertical: 5),
                                                      child: Text(
                                                        "取消",
                                                        style: TextStyle(
                                                            color:
                                                                Colors.white),
                                                      ),
                                                    ))),
                                            const SizedBox(
                                              width: 20,
                                            ),
                                            InkWell(
                                                onTap: () {
                                                  Navigator.pop(context, true);
                                                },
                                                child: Container(
                                                    decoration:
                                                        const BoxDecoration(
                                                            color: Colors.blue,
                                                            borderRadius:
                                                                BorderRadius
                                                                    .all(Radius
                                                                        .circular(
                                                                            5))),
                                                    child: const Padding(
                                                      padding:
                                                          EdgeInsets.symmetric(
                                                              horizontal: 15,
                                                              vertical: 5),
                                                      child: Text(
                                                        "确定",
                                                        style: TextStyle(
                                                            color:
                                                                Colors.white),
                                                      ),
                                                    ))),
                                          ],
                                        ),
                                      )
                                    ],
                                  ));
                          if (res != null && res) {
                            await SqlManager.deleteById(
                                "${list![index]["id"]}");
                            init();
                          }
                        },
                        child: Padding(
                          padding: const EdgeInsets.only(right: 10),
                          child: Row(
                            children: [
                              Expanded(
                                  flex: 1,
                                  child: Center(
                                      child: Text(
                                          "${list![index]["month"]}月${list![index]["day"]}日",
                                          style: const TextStyle(
                                              fontWeight: FontWeight.bold)))),
                              Expanded(
                                flex: 4,
                                child: Center(
                                  child: Container(
                                    decoration: BoxDecoration(
                                        border: Border.all(
                                            color: Colors.black,
                                            width: 1,
                                            style: BorderStyle.solid)),
                                    child: Row(
                                      children: [
                                        Padding(
                                            padding: const EdgeInsets.symmetric(
                                                horizontal: 20, vertical: 10),
                                            child: Text(list![index]["reason"]
                                                .toString())),
                                        Padding(
                                            padding: const EdgeInsets.symmetric(
                                                horizontal: 20, vertical: 10),
                                            child: Text(list![index]["money"]
                                                    .toString() +
                                                "元")),
                                      ],
                                      mainAxisAlignment:
                                          MainAxisAlignment.spaceBetween,
                                    ),
                                  ),
                                ),
                              )
                            ],
                          ),
                        ),
                      );
                    },
                    separatorBuilder: (context, index) {
                      return const Divider();
                    },
                    itemCount: list!.length),
              )
          ],
        )),
        Padding(
          padding: const EdgeInsets.symmetric(vertical: 10),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              InkWell(
                onTap: () {
                  Navigator.push(
                      context,
                      MaterialPageRoute(
                          builder: (c) => const AgreementPage(
                              justLook: true, isAgreement: false)));
                },
                child: const Padding(
                  padding: EdgeInsets.all(8.0),
                  child: Text(
                    "《隐私政策》",
                    style: TextStyle(color: Colors.blue),
                  ),
                ),
              ),
              InkWell(
                onTap: () {
                  Navigator.push(
                      context,
                      MaterialPageRoute(
                          builder: (c) => const AgreementPage(
                              justLook: true, isAgreement: true)));
                },
                child: const Padding(
                  padding: EdgeInsets.all(8.0),
                  child: Text(
                    "《服务条款》",
                    style: TextStyle(color: Colors.blue),
                  ),
                ),
              ),
            ],
          ),
        )
      ],
    ));
  }
}
